<?php
/*****************************************************

  Copyright:	(c) 2006  SeaDesign Web Studio
        Web:	www.seadesign.ru
      Email: 	seadesign@gmail.com
  
*****************************************************/

require_once('data.inc');

class Banner 
{
	function __construct($typeId) 
	{
		$count = query2var("
			SELECT COUNT(*) 
			FROM cf_banners 
			WHERE type_id=$typeId
			  AND (display_times IS NULL OR display_times>0)
			  AND (display_from IS NULL OR NOW() >= display_from)
			  AND (display_to IS NULL OR NOW() < display_to)
		");
		
		$randomSkip = rand(0,$count-1);
		
		$params = query2array("
				SELECT cf_banners.id,cf_banners.name,url,cf_url_targets.name AS target,image,width,height
				FROM cf_banners 
				INNER JOIN cf_banner_types ON cf_banners.type_id = cf_banner_types.id
				INNER JOIN cf_url_targets ON cf_banners.target = cf_url_targets.id
				WHERE type_id=$typeId
				  AND (display_times IS NULL OR display_times>0)
				  AND (display_from IS NULL OR NOW() >= display_from)
				  AND (display_to IS NULL OR NOW() < display_to)
				LIMIT $randomSkip,1
			");

		$this->id = $params['id'];
		$this->name = $params['name'];
		$this->url = $params['url'];
		$this->target = $params['target'];
		$this->image = '/'.$params['image'];
		$this->path = $_SERVER['DOCUMENT_ROOT'].$this->image;
		$this->width = $params['width'];
		$this->height = $params['height'];
	}
	
	public function onDisplay()
	{
		if (!$this->exists()){
			return;
		}
		
		execQuery(
			"UPDATE cf_banners SET display_times=display_times-1 WHERE id={$this->id} AND display_times IS NOT NULL AND display_times > 0"
		);
	}
	
	public function exists()
	{
		return !is_null($this->id);
	}

	public function name()
	{
		return $this->name;
	}
	
	public function image()
	{
		return $this->image;
	}
	
	public function path()
	{
		return $this->path;
	}
	
	public function url()
	{
		return $this->url;
	}

	public function target()
	{
		return $this->target;
	}
	
	public function width()
	{
		return $this->width;
	}
	
	public function height()
	{
		return $this->height;
	}
	
	private $id = null;
	private $name = null;
	private $url = null;
	private $target = null;
	private $image = null;
	private $path = null;
	private $width = null;
	private $height = null;
};

?>